package com.google.android.apps.wakemewhere;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;

public class AlarmDatabase extends SQLiteOpenHelper {

	private static final String DATABASE_NAME = "WakeMeWhere.db";
	private static final String TABLE_NAME = "alarms";
	private static final int DATABASE_VERSION = 5;
	
    public static final String[] QUERY_COLUMNS = { 
    	"_id", 
    	"label", 
    	"latitude_e6", 
    	"longitude_e6", 
    	"enabled",
    	"exited",
    	"vibrate"
    };
    
	private static final String NULL_COLUMN_HACK = "label"; 
    
	public AlarmDatabase(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		db.execSQL("CREATE TABLE " + TABLE_NAME + " ("
				+ "_id INTEGER PRIMARY KEY AUTOINCREMENT," 
				+ "label TEXT,"
				+ "latitude_e6 INTEGER," 
				+ "longitude_e6 INTEGER,"
				+ "enabled INTEGER, "
				+ "exited INTEGER, "
				+ "vibrate INTEGER)"
				);
	}
	
	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
		onCreate(db);
	}
	
	public Cursor alarmsListCursor(String[] columns, String selection, 
			String[] selectionArgs, String sort) {
		return getReadableDatabase().query(TABLE_NAME, columns, selection, 
				selectionArgs, null, null, sort);
	}
	
	public Cursor alarmCursorById(long id, String[] projection, 
			String selection, String[] selectionArgs, String sortOrder) {
		SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
		queryBuilder.setTables(TABLE_NAME);
		queryBuilder.appendWhere("_id=");
		queryBuilder.appendWhere("" + id);
		return queryBuilder.query(getReadableDatabase(), projection, selection,
				selectionArgs, null, null, sortOrder); 
	}

	public int delete(String where, String[] whereArgs) {
		return getWritableDatabase().delete(TABLE_NAME, where, whereArgs);
	}

	public int update(long id, ContentValues values) {
		return getWritableDatabase().update(TABLE_NAME, values, "_id=" + id, null);
	}
	
	public long insert(ContentValues values) {
		long rowId = getWritableDatabase().insert(
				TABLE_NAME, NULL_COLUMN_HACK, values);
		if (rowId < 0) {
			throw new SQLException("Failed to insert row");
		}
		return rowId;
	}
}	
